//
//  ViewController.swift
//  Progress
//
//  Created by bin hu on 2025/6/25.
//

import UIKit

extension Optional {
    var description: String {
        switch self {
        case .some(let value): return String(describing: value)
        case .none: return "nil"
        }
    }
}

public func log(_ lastMessage: @autoclosure () -> Any,
                file: StaticString = #file,
                line: UInt = #line) {
#if DEBUG
    let fileStr = "\(file)"
    let className = fileStr.components(separatedBy: "/").last?.components(separatedBy: ".").first ?? ""
    debugPrint("🌹🌹文件：\(className)_.^._第\(line)行_.^._日志信息：\(lastMessage())🌹🌹")
#endif
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        // 使用示例
        let progressBar = RingProgressBar(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
        progressBar.center = view.center
        view.addSubview(progressBar)
        progressBar.setProgress(0.4913) // 设置买入进度
        
        setUI()
        
    }

}

extension ViewController {
    func setUI() {
        // 创建水平排列的StackView
        let stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.distribution = .fillEqually
        stackView.spacing = 20
        stackView.translatesAutoresizingMaskIntoConstraints = false
        
        // 创建第一个按钮
        let button1 = UIButton(type: .system)
        button1.setTitle("URLSessionWebSocketTask", for: .normal)
        button1.addTarget(self, action: #selector(testSocket), for: .touchUpInside)
        button1.backgroundColor = .blue
        button1.tintColor = .white
        
        // 创建第二个按钮
        let button2 = UIButton(type: .system)
        button2.setTitle("SocketIO", for: .normal)
        button2.addTarget(self, action: #selector(dynamicDomain), for: .touchUpInside)
        button2.backgroundColor = .red
        button2.tintColor = .white
        
        // 将按钮添加到StackView
        stackView.addArrangedSubview(button1)
        stackView.addArrangedSubview(button2)
        
        // 将StackView添加到视图
        view.addSubview(stackView)
        
        // 约束：贴底 + 水平居中 + 宽度80%
        NSLayoutConstraint.activate([
            stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            stackView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor, constant: -20),
            stackView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.8),
            stackView.heightAnchor.constraint(equalToConstant: 50)
        ])
        // 设置约束 整体居中
//        NSLayoutConstraint.activate([
//            stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
//            stackView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
//            stackView.widthAnchor.constraint(equalTo: view.widthAnchor, multiplier: 0.8)
//        ])
    }
}

extension ViewController {
    
    @objc func testSocket() {
        ///
        let manager = WebSocketManager(url: URL(string: "ws://112.121.161.67:10095"/*"wss://echo.websocket.org"*/)!)
        
        // 设置回调
        manager.onConnect = {
            log("连接建立成功")
            Task {
                try await manager.send("Hello WebSocket")
            }
        }

        manager.onMessage = { message in
            switch message {
            case .string(let text):
                    log("收到文本消息: \(text)")
            case .data(let data):
                    log("收到二进制数据: \(data)")
            @unknown default:
                break
            }
        }

        manager.onDisconnect = { error in
            log("连接断开: \(error?.localizedDescription ?? "未知错误")")
        }

        // 启动连接
        manager.connect()
    }
    
}

extension ViewController {
    
    @objc func dynamicDomain() {
        
        SocketConnectionManager.shared.addListener(for: "customEvent") { payload in
            log("处理自定义事件:\(payload)")
            /// 业务逻辑
        }
        
        SocketConnectionManager.shared.emit("sendMessage", "跟你说话呢","2025")
    }
    
}

